package com.pc.scrs.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pc.scrs.utils.ResponseResult;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录失败的处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //AuthenticationException就是异常对象
        System.out.println(e);

        //设置响应数据的编码格式
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        //将ResponseResult转为json
        ObjectMapper mapper=new ObjectMapper();
        String json=null;

        if(e instanceof InternalAuthenticationServiceException){
            json= mapper.writeValueAsString(new ResponseResult<>(4001, "帐号不存在！"));
        }else if(e instanceof BadCredentialsException){
            json= mapper.writeValueAsString(new ResponseResult<>(4002, "密码错误！"));
        }else if(e instanceof LockedException){
            json= mapper.writeValueAsString(new ResponseResult<>(4003, "账号被锁定，请联系管理员！"));
        }else if(e instanceof DisabledException){
            json= mapper.writeValueAsString(new ResponseResult<>(4004, "账号被禁用，请联系管理员！"));
        }else if(e instanceof CredentialsExpiredException){
            json= mapper.writeValueAsString(new ResponseResult<>(4005, "密码已过期，请联系管理员！"));
        }else if(e instanceof AccountExpiredException){
            json= mapper.writeValueAsString(new ResponseResult<>(4006, "账号已过期，请联系管理员！"));
        }

        PrintWriter out= httpServletResponse.getWriter();
        out.write(json);
        out.close();
    }
}
